import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/settings_provider.dart';
import '../constants/app_theme.dart';
import 'home_screen.dart';
import 'history_screen.dart';
import 'analytics_screen.dart';
import 'settings_screen.dart';

import '../constants/app_routes.dart';

/// 主导航页面
/// 包含底部导航栏和主要页面的容器
class MainScreen extends StatefulWidget {
  const MainScreen({super.key});

  @override
  State<MainScreen> createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> with TickerProviderStateMixin {
  int _currentIndex = 0;
  late PageController _pageController;

  /// 底部导航页面列表
  final List<Widget> _pages = [
    const HomeScreen(),
    const HistoryScreen(),
    const AnalyticsScreen(),
    const SettingsScreen(),
  ];

  /// 底部导航项配置
  final List<BottomNavigationBarItem> _navigationItems = [
    const BottomNavigationBarItem(
      icon: Icon(Icons.home_outlined),
      activeIcon: Icon(Icons.home),
      label: '首页',
    ),
    const BottomNavigationBarItem(
      icon: Icon(Icons.history_outlined),
      activeIcon: Icon(Icons.history),
      label: '历史',
    ),
    const BottomNavigationBarItem(
      icon: Icon(Icons.analytics_outlined),
      activeIcon: Icon(Icons.analytics),
      label: '分析',
    ),
    const BottomNavigationBarItem(
      icon: Icon(Icons.settings_outlined),
      activeIcon: Icon(Icons.settings),
      label: '设置',
    ),
  ];

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: _currentIndex);
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<SettingsProvider>(builder: (context, settings, child) {
      return Scaffold(
        body: Stack(
          children: [
            // 主要内容页面
            Positioned.fill(
              child: PageView(
                controller: _pageController,
                onPageChanged: _onPageChanged,
                children: _pages,
              ),
            ),
            // 悬浮底部导航栏
            Positioned(
              left: 0,
              right: 0,
              bottom: 0,
              child: _buildFloatingBottomNavigationBar(),
            ),
          ],
        ),
      );
    });
  }

  /// 构建现代化悬浮磨砂玻璃风格底部导航栏
  Widget _buildFloatingBottomNavigationBar() {
    return Container(
      margin: const EdgeInsets.fromLTRB(16, 0, 16, 24), // 优化边距
      child: ClipRRect(
        borderRadius: BorderRadius.circular(32),
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 25, sigmaY: 25),
          child: Container(
            height: 90,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(32),
              // 多层渐变背景 - 调浅背景颜色
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Colors.white.withOpacity(0.4),
                  Colors.white.withOpacity(0.3),
                  Colors.white.withOpacity(0.25),
                ],
                stops: const [0.0, 0.5, 1.0],
              ),
              border: Border.all(
                color: Colors.white.withOpacity(0.4),
                width: 1.5,
              ),
              boxShadow: [
                // 主要阴影 - 增强悬浮感
                BoxShadow(
                  color: Colors.black.withOpacity(0.15),
                  spreadRadius: 0,
                  blurRadius: 20,
                  offset: const Offset(0, 8),
                ),
                // 内部高光
                BoxShadow(
                  color: Colors.white.withOpacity(0.3),
                  spreadRadius: 0,
                  blurRadius: 10,
                  offset: const Offset(0, -2),
                ),
                // 底部深度阴影
                BoxShadow(
                  color: Colors.black.withOpacity(0.08),
                  spreadRadius: 2,
                  blurRadius: 30,
                  offset: const Offset(0, 12),
                ),
              ],
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: _buildNavigationItems(),
            ),
          ),
        ),
      ),
    );
  }

  /// 构建导航项列表
  List<Widget> _buildNavigationItems() {
    return [
      _buildNavigationItem(Icons.home_rounded, '首页', 0),
      _buildNavigationItem(Icons.timeline_rounded, '时间线', 1),
      _buildRecordButton(), // 中间的记录心情按钮
      _buildNavigationItem(Icons.calendar_today_rounded, '日历', 3),
      _buildNavigationItem(Icons.settings_rounded, '设置', 4),
    ];
  }

  /// 构建现代化磨砂玻璃风格导航项
  Widget _buildNavigationItem(IconData icon, String label, int index) {
    // 调整选中状态判断：因为中间插入了记录按钮，所以索引3和4需要减1
    int pageIndex = index > 2 ? index - 1 : index;
    final isSelected = _currentIndex == pageIndex;
    
    return GestureDetector(
      onTap: () => _onTabTapped(index),
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOutCubic,
        padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 图标容器 - 现代化设计（固定尺寸避免布局重排）
            AnimatedScale(
              duration: const Duration(milliseconds: 300),
              curve: Curves.easeInOutCubic,
              scale: isSelected ? 1 : 1.0,
              child: Container(
                width: 48, // 固定尺寸
                height: 48, // 固定尺寸
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(isSelected ? 16 : 12),
                  gradient: isSelected 
                    ? LinearGradient(
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                        colors: [
                          Colors.blue.shade400.withOpacity(0.9),
                          Colors.blue.shade600.withOpacity(0.9),
                          Colors.blue.shade700.withOpacity(0.9),
                        ],
                        stops: const [0.0, 0.5, 1.0],
                      )
                    : null,
                  color: isSelected ? null : Colors.transparent,
                  boxShadow: isSelected ? [
                    // 主要阴影 - 增强立体感
                    BoxShadow(
                      color: Colors.blue.withOpacity(0.4),
                      spreadRadius: 0,
                      blurRadius: 12,
                      offset: const Offset(0, 4),
                    ),
                    // 内部高光
                    BoxShadow(
                      color: Colors.white.withOpacity(0.3),
                      spreadRadius: 0,
                      blurRadius: 6,
                      offset: const Offset(0, -1),
                    ),
                    // 底部深度阴影
                    BoxShadow(
                      color: Colors.blue.shade900.withOpacity(0.2),
                      spreadRadius: 0,
                      blurRadius: 8,
                      offset: const Offset(0, 6),
                    ),
                  ] : [
                    // 未选中状态的轻微阴影
                    BoxShadow(
                      color: Colors.black.withOpacity(0.05),
                      spreadRadius: 0,
                      blurRadius: 4,
                      offset: const Offset(0, 2),
                    ),
                  ],
                  border: isSelected ? Border.all(
                    color: Colors.white.withOpacity(0.4),
                    width: 1.5,
                  ) : null,
                ),
                child: Icon(
                  icon,
                  color: isSelected ? Colors.white : Colors.grey.shade600,
                  size: isSelected ? 24 : 20,
                ),
              ),
            ),
            const SizedBox(height: 3),
            // 文字标签 - 优化排版
            AnimatedDefaultTextStyle(
              duration: const Duration(milliseconds: 300),
              curve: Curves.easeInOutCubic,
              style: TextStyle(
                color: isSelected ? Colors.blue.shade700 : Colors.grey.shade600,
                fontSize: isSelected ? 12 : 11,
                fontWeight: isSelected ? FontWeight.w700 : FontWeight.w500,
                letterSpacing: isSelected ? 0.5 : 0.2,
                height: 1.2,
              ),
              child: Text(
                label,
                textAlign: TextAlign.center,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
      ),
    );
  }



  /// 处理标签页点击
  void _onTabTapped(int index) {
    // 如果点击的是中间的记录按钮（索引2），直接返回，不切换页面
    if (index == 2) {
      return;
    }
    
    // 调整索引：因为中间插入了记录按钮，所以索引3和4需要减1
    int pageIndex = index > 2 ? index - 1 : index;
    
    if (pageIndex != _currentIndex) {
      setState(() {
        _currentIndex = pageIndex;
      });
      
      _pageController.animateToPage(
        pageIndex,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }

  /// 处理页面变化
  void _onPageChanged(int index) {
    if (index != _currentIndex) {
      setState(() {
        _currentIndex = index;
      });
    }
  }

  /// 构建现代化中间记录心情按钮
  Widget _buildRecordButton() {
    return GestureDetector(
      onTap: _onRecordButtonPressed,
      child: Container(
        width: 50,
        height: 50,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          // 多层渐变 - 增强立体感（调淡版本）
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              Colors.blue.shade200.withOpacity(0.8),
              Colors.blue.shade300.withOpacity(0.9),
              Colors.blue.shade400.withOpacity(0.9),
              Colors.blue.shade500.withOpacity(0.9),
            ],
            stops: const [0.0, 0.3, 0.7, 1.0],
          ),
          border: Border.all(
            color: Colors.white.withOpacity(0.5),
            width: 2,
          ),
          boxShadow: [
            // 主要阴影（调淡）
            BoxShadow(
              color: Colors.blue.withOpacity(0.25),
              spreadRadius: 0,
              blurRadius: 16,
              offset: const Offset(0, 6),
            ),
            // 内部高光
            BoxShadow(
              color: Colors.white.withOpacity(0.4),
              spreadRadius: 0,
              blurRadius: 8,
              offset: const Offset(0, -3),
            ),
            // 底部深度阴影（调淡）
            BoxShadow(
              color: Colors.blue.shade700.withOpacity(0.2),
              spreadRadius: 0,
              blurRadius: 20,
              offset: const Offset(0, 10),
            ),
            // 环形光晕（调淡）
            BoxShadow(
              color: Colors.blue.withOpacity(0.15),
              spreadRadius: 4,
              blurRadius: 24,
              offset: const Offset(0, 0),
            ),
          ],
        ),
        child: Container(
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            gradient: RadialGradient(
              center: const Alignment(-0.3, -0.3),
              radius: 1.2,
              colors: [
                Colors.white.withOpacity(0.3),
                Colors.transparent,
              ],
            ),
          ),
          child: const Icon(
            Icons.add_rounded,
            color: Colors.white,
            size: 32,
          ),
        ),
      ),
    );
  }

  /// 处理记录按钮点击事件
  void _onRecordButtonPressed() {
    Navigator.pushNamed(context, '/record');
  }


}

/// 自定义底部导航栏
class CustomBottomNavigationBar extends StatelessWidget {
  final int currentIndex;
  final ValueChanged<int> onTap;
  final List<BottomNavigationBarItem> items;

  const CustomBottomNavigationBar({
    super.key,
    required this.currentIndex,
    required this.onTap,
    required this.items,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 90,
      decoration: BoxDecoration(
        color: Theme.of(context).scaffoldBackgroundColor,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.1),
            blurRadius: 10,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: Row(
        children: items.asMap().entries.map((entry) {
          final index = entry.key;
          final item = entry.value;
          final isSelected = currentIndex == index;
          
          return Expanded(
            child: InkWell(
              onTap: () => onTap(index),
              child: Container(
                padding: const EdgeInsets.symmetric(vertical: 4),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Flexible(
                      flex: 3,
                      child: AnimatedContainer(
                        duration: const Duration(milliseconds: 200),
                        padding: const EdgeInsets.all(4),
                        decoration: BoxDecoration(
                          color: isSelected
                              ? AppTheme.primaryColor.withValues(alpha: 0.1)
                              : Colors.transparent,
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: AnimatedSwitcher(
                          duration: const Duration(milliseconds: 200),
                          child: Icon(
                            isSelected
                                ? (item.activeIcon as Icon).icon
                                : (item.icon as Icon).icon,
                            color: isSelected
                                ? AppTheme.primaryColor
                                : AppTheme.textSecondaryColor,
                            size: 20,
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(height: 1),
                    Flexible(
                      flex: 1,
                      child: AnimatedDefaultTextStyle(
                        duration: const Duration(milliseconds: 200),
                        style: TextStyle(
                          fontSize: 10,
                          fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
                          color: isSelected
                              ? AppTheme.primaryColor
                              : AppTheme.textSecondaryColor,
                          height: 1.0,
                        ),
                        child: Text(
                          item.label!,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          textAlign: TextAlign.center,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }
}